<?php
namespace lib;

use \Firebase\JWT\JWT;

/**
 * 单例 一次请求中所有使用jwt的地方都是一个用户
 *
 */
class JwtAuth
{
    private $token;
    private static $instance;

    private $iss = 'api.tets.com'; //签发人
    private $aud = 'api.tets.com'; //受众
    private $key = '#dsafasieg92fsdyhb3290&$#%#@342';

    private $uid;
    /**
     * 单例模式 JwtAuth句柄
     */
    public static function getInstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function __construct()
    {
    }

    private function __clone(){
    }

    public function encode()
    {
        $time = time();
        $payload = array(
            "iss" => $this->iss,
            "aud" => $this->aud,
            "iat" => $time,
            "nbf" => $time,
            "uid" => $this->uid
        );
        $this->token = $jwt = JWT::encode($payload, $this->key);

        return $this;
    }

    public function getToken()
    {
        return (string)$this->token;
    }

    public function setToken($token)
    {
        $this->token = $token;
        return $this;
    }

    public function setUid($uid)
    {
        $this->uid = $uid;
        return $this;
    }

    public function decode($token)
    {
        $decoded = JWT::decode($token, $this->key, array('HS256'));
        return $decoded;
    }

}